// S1MFileUploadProgressUtils.js

var S1MFileUploadProgressUtils = (function($) {
  "use strict";

  var fileUploladProgressCheckIntervalDefault = 2; // seconds
  var fileUploadProgressTimer;

  var prepareToObserveFileUpload = function() {
    var data = {};
    data[IParameterName.TAG_ACTION] = IActionName.CREATE_FILE_UPLOAD_PROGRESS_OBSRV;
    S1MUtils.call(data, startFileUploadProgressTimer, undefined);
  };

  // This method sets the time interval to call checkFileUploadStatus method.
  var startFileUploadProgressTimer = function() {
	resetFileUploadModalAndStatusCheckTimerFl = false;// SF_31448
    var fileUploladProgressCheckInterval = IConfigParameterName.FILE_UPLOAD_PROGRESS_CHECK_INTERVAL;// millisecond
    if (isNaN(fileUploladProgressCheckInterval)) {
      fileUploladProgressCheckInterval = fileUploladProgressCheckIntervalDefault;
    }
    fileUploladProgressCheckInterval = fileUploladProgressCheckInterval * 1000;// seconds
    fileUploadProgressTimer = setInterval(checkFileUploadStatus, fileUploladProgressCheckInterval);
  };

  // This method calls the checkFileUploadStatus of the
  // SubmissionAjaxController class to check the file upload current status.
  var checkFileUploadStatus = function() {
    var data = {};
    data[IParameterName.TAG_ACTION] = IActionName.CHECK_FILE_UPLOAD_STATUS;
    S1MUtils.call(data, displayProgressText, undefined);
    if (resetFileUploadModalAndStatusCheckTimerFl)
      resetFileUploadModalAndStatusCheckTimer(); //SF-28473 stop after running fileUploadCompleted(). Otherwise, it goes into infinite loop
  };

  /**
   * This is the callback method which writes the status text values into the modal.
   */
  var displayProgressText = function(jsonPayload) {
    if (jsonPayload == undefined || jsonPayload[IParameterName.FILE_UPLOAD_PROGRESS_VO] == undefined) {
      ; // do nothing. this condition can happen when an upload starts on a very slow connection
    } else {
      var fileUploadProgressVO = jsonPayload[IParameterName.FILE_UPLOAD_PROGRESS_VO];
      var progressTexts = fileUploadProgressVO.progressTexts;
      if (progressTexts != undefined && progressTexts.length > 0) {
        for (var i = 0; i < progressTexts.length; i++) {
          $('#progressModal .modal-message').html(progressTexts[i]);
        }
      }
      // notice that this function never closes the modal. caller is responsible for closing modal at end of observed process.
    }
  };

  // This method clears the time interval and closes the modal.
  var resetFileUploadModalAndStatusCheckTimer = function() {
    clearInterval(fileUploadProgressTimer);
    $('#progressModal').modal('hide');
  };

  return {
    prepareToObserveFileUpload : prepareToObserveFileUpload,
    resetFileUploadModalAndStatusCheckTimer : resetFileUploadModalAndStatusCheckTimer
  };
})(jQuery);
